package com.smssalama.storage.framework;

import java.io.IOException;

import javax.microedition.rms.RecordComparator;

import org.bouncycastle.crypto.CryptoException;

public class StorableComparatorImpl implements RecordComparator, StorableComparator {

	// public static final StorableComparatorImpl DEFAULT = new
	// StorableComparatorImpl();
	private StorageEncryptor encryptor;
	private Object[] criteria = null;

	protected StorableComparatorImpl(StorageEncryptor encryptor) {
		this.encryptor = encryptor;
	}

	public static StorableComparatorImpl getDefault(StorageEncryptor encryptor) {
		return new StorableComparatorImpl(encryptor);
	}

	public StorableComparatorImpl(Object[] criteria) {
		this.criteria = criteria;
	}

	public int compare(Storable s1, Storable s2) {
		if (this.criteria == null) {
			return s1.compareTo(s2);
		} else {
			for (int i = 0; i < this.criteria.length; i++) {
				int result = s1.compareTo(s2, this.criteria[i]);
				if (result != 0) {
					return result;
				}				
			}
			return 0;
		}		
	}

	public int compare(byte[] arg0, byte[] arg1) {
		try {
			if (this.encryptor != null) {
				arg0 = this.encryptor.decrypt(arg0);
				arg1 = this.encryptor.decrypt(arg1);
			}
			Storable s1 = Storable.init(arg0);
			Storable s2 = Storable.init(arg1);
			
			return compare(s1, s2);
		} catch (ObjectStorageException e) {
			e.printStackTrace();
			throw new RuntimeException("Object comparison failed: "
					+ e.getMessage());
		} catch (IOException e) {
			e.printStackTrace();
			return 0;
		} catch (CryptoException e) {
			e.printStackTrace();
			throw new RuntimeException(
					"Failed to decrypt object. Comparison failed: "
							+ e.getMessage());
		}
	}

	public boolean terminate() {
		return false;
	}

}
